import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

/**
 * @author: knowno
 * @create: 2025-09-17 09:14
 * @Version 1.0
 **/
public class TestFileCopyChannel {
    public static void main(String[] args) {
        String srcPath="G:\\apache-seata-2.1.0-incubating-bin.tar.gz";

        String destPath="F:\\seata-2.1.0-incubating-bin.tar.gz";

        copyfile(srcPath,destPath);

    }
    /**
     * 复制文件
     * @param srcPath  源文件路径
     * @param destPath 目标文件路径
     */
    public  static  void copyfile(String srcPath,String destPath){


        //创建字节流 =>输出流
        FileOutputStream fileOutputStream = null;
        //创建字节流 =>输入流
        FileInputStream fileInputStream = null;

        FileChannel fileChannelIn = null;
        FileChannel fileChannelOut = null;
        try {
            //从原始位置读取数据
            fileInputStream = new FileInputStream(srcPath);
            //将数据写入目标位置
            fileOutputStream = new FileOutputStream(destPath);

            //创建通道
            fileChannelIn = fileInputStream.getChannel();
            fileChannelOut = fileOutputStream.getChannel();

            //TransferTo 方法
            fileChannelIn.transferTo(0,fileChannelIn.size(),fileChannelOut);

            //提示
            System.out.println("文件复制成功");




        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭通道
            if(fileChannelIn!=null){
                try {
                    fileChannelIn.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(fileChannelOut!=null){
                try {
                    fileChannelOut.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }


            //关闭流
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
}
